﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RTracker.Models.Organization;
using RTracker.Models.Common;
using JsonConversion;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using System.Diagnostics;

namespace RTracker.Controllers
{
    public class OrganizationController : AppBaseController
    {
        //
        // GET: /Organization/

        /// <summary>
        /// Save method
        /// </summary>
        /// <param name="oGOrganization"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Save(GOrganization oGOrganization)
        {

            try
            {
                //check if Model validation is true if not then return detail view with errors
                if (true)//ModelState.IsValid
                {
                    //call CheckSession to get session status
                    string SessionState = CheckSessionState();
                    //check if session state is ok else return false status to view.
                    if (SessionState == CAppConstants.SessionSuccess)
                    {
                        bool _userPermission = false;

                        if (oGOrganization.Organization.OrganizationId == 0)
                        {
                            _userPermission = checkUserPermission(CUserPermissionsConstants.OrganizationCreate);
                        }
                        else
                        {
                            _userPermission = checkUserPermission(CUserPermissionsConstants.OrganizationUpdate);
                        }


                        if (_userPermission)
                        {
                            COrganization objCOrganization = new COrganization();
                            objCOrganization = oGOrganization.Organization;
                            MOrganization objMOrganization = new MOrganization();
                           
                            if (objCOrganization.OrganizationId == 0)
                            {
                                objCOrganization.OrganizationId = CurrentUserSession.OrganizationId;
                                oGOrganization.Status = objMOrganization.CreateOrganization(AuthenticationContext, ref objCOrganization);
                            }
                            else
                            {
                                oGOrganization.Status = objMOrganization.UpdateOrganization(AuthenticationContext, ref objCOrganization);
                            }
                        }
                        else
                        {
                            oGOrganization.Status = new CStatus();
                            oGOrganization.Status.Success = false;
                            oGOrganization.Status.StatusDetails = CAppErrorsConstants.NoPermission;
                        }
                    }
                    else
                    {
                        oGOrganization.Status = new CStatus();
                        oGOrganization.Status.Success = false;
                        oGOrganization.Status.StatusDetails = SessionState;
                    }
                }
                else
                {
                    oGOrganization.Status = new CStatus();
                    oGOrganization.Status.Success = false;
                    oGOrganization.Status.StatusDetails = CAppErrorsConstants.ValidationFail;
                }
            }
            catch (Exception ex)
            {
                oGOrganization.Status = new CStatus();
                oGOrganization.Status.Success = false;
                oGOrganization.Status.StatusDetails = ex.Message;
            }
            return Json(oGOrganization);
        }

        /// <summary>
        /// GetOrganizationDetails
        /// </summary>
        /// <param name="pnId">record id</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetDetails(int pnId)
        {
            GOrganization objGOrganization = new GOrganization();

            objGOrganization.Status = new CStatus();

            objGOrganization.Organization = new COrganization();

            objGOrganization.Organization.OrganizationId = pnId;

            COrganization objCOrganization = new COrganization();

            ViewBag.IsDisabled = true;
            try
            {
                //call CheckSession to get session status
                string SessionState = CheckSessionState();

                //IsDisabled checks whether cureently selected row is hardlocked or softlocked by other
                ViewBag.IsDisabled = true;
                ViewBag.IsNew = false;
                //check if session state is ok else return false status to view.
                if (SessionState == CAppConstants.SessionSuccess)
                {
                    //check if Id param is 0 means new is clicked then set selected row object to new.
                    if (0 == pnId)
                    {
                        if (checkUserPermission(CUserPermissionsConstants.OrganizationCreate))
                        {
                            //here we will append new form to create new organisation
                            ViewBag.IsNew = true;
                            objGOrganization.Status.Success = true;
                            objGOrganization.Status.StatusDetails = CAppConstants.DetailSuccess;
                        }
                        else
                        {
                            objGOrganization.Status.Success = false;
                            objGOrganization.Status.StatusDetails = CAppErrorsConstants.NoPermission;
                        }
                    }
                    else
                    {
                        if (checkUserPermission(CUserPermissionsConstants.OrganizationDetailView))
                        {
                            //here we will append new for detail 
                            MOrganization objMOrganization = new MOrganization();

                            ViewBag.IsNew = false;

                            objCOrganization.OrganizationId = objGOrganization.Organization.OrganizationId;

                            objGOrganization.Status = objMOrganization.GetOrganizationDetail(AuthenticationContext, ref objCOrganization);

                            //get the different admin names from their id from the application Organization list
                            objCOrganization.CreatedByName = GetFullName(objCOrganization.CreatedBy);
                            objCOrganization.ModifiedByName = GetFullName(objCOrganization.ModifiedBy);
                            objCOrganization.SoftLockedByName = GetFullName(objCOrganization.SoftLockedBy);
                            objCOrganization.HardLockedByName = GetFullName(objCOrganization.HardLockedBy);


                            if (!CheckLocksByOther(objCOrganization))
                            {
                                ViewBag.IsDisabled = false;
                            }
                            if (objGOrganization.Status.Success == true)
                            {
                                objGOrganization.Organization = objCOrganization;
                            }
                        }
                        else
                        {
                            objGOrganization.Status = new CStatus();
                            objGOrganization.Status.Success = false;
                            objGOrganization.Status.StatusDetails = CAppErrorsConstants.NoPermission;
                        }
                    }
                }
                else
                {
                    objGOrganization.Status = new CStatus();
                    objGOrganization.Status.Success = false;
                    objGOrganization.Status.StatusDetails = SessionState;
                }
            }
            catch (Exception ex)
            {

                objGOrganization.Status = new CStatus();
                objGOrganization.Status.Success = false;
                objGOrganization.Status.StatusDetails = ex.Message;
            }

            return PartialView("_detail", objGOrganization);
        }
        
        [HttpPost]
        public ActionResult Delete(string pstrIds)
        {
            GOrganization objGOrganization = new GOrganization();
            try
            {
                //call CheckSession to get session status
                string SessionState = CheckSessionState();

                //check if session state is ok else return false status to view.
                if (SessionState == CAppConstants.SessionSuccess)
                {
                    if (pstrIds.Trim() != "")
                    {
                        if (checkUserPermission(CUserPermissionsConstants.OrganizationDelete))
                        {
                            COrganization objCOrganization = new COrganization();

                            objCOrganization.OrganizationIds = pstrIds;

                            MOrganization objMOrganization = new MOrganization();

                            objGOrganization.Status = objMOrganization.DeleteOrganization(objCOrganization, AuthenticationContext);
                        }
                        else
                        {
                            objGOrganization.Status.Success = false;
                            objGOrganization.Status.StatusDetails = CAppErrorsConstants.NoPermission;
                        }
                    }
                    else
                    {
                        objGOrganization.Status = new CStatus();
                        objGOrganization.Status.Success = false;
                        objGOrganization.Status.StatusDetails = CAppErrorsConstants.SomethingWentWrong;
                    }
                }
                else
                {
                    objGOrganization.Status = new CStatus();
                    objGOrganization.Status.Success = false;
                    objGOrganization.Status.StatusDetails = SessionState;
                }
            }
            catch (Exception ex)
            {

                objGOrganization.Status = new CStatus();
                objGOrganization.Status.Success = false;
                objGOrganization.Status.StatusDetails = ex.Message;
            }

            return Json(objGOrganization.Status);
        }

        [HttpPost]
        public ActionResult GridRefresh(int pnId, string pstrSortOn, string pstrSortType, int pnPageNo, int pnPageSize, string pstrSearch, string pstrSearchOn, int pnOrgId = 1)
        {

            GOrganization objGOrganization = new GOrganization();
            objGOrganization.LstCOrganization = new List<COrganization>();
            try
            {
                if (pstrSearch == null || pstrSearchOn == null)
                {
                    pstrSearch = "";
                    pstrSearchOn = "";
                }

                //call CheckSession to get session status
                string SessionState = CheckSessionState();

                //check if session state is ok else return false status to view.
                if (SessionState == CAppConstants.SessionSuccess)
                {
                    COrganization objCOrganization = new COrganization() { OrganizationId = pnId, SortOn = pstrSortOn, SortType = pstrSortType, PageNumber = pnPageNo,RowSize = pnPageSize, Search = pstrSearch, SearchOn = pstrSearchOn};


                    //check if current users organization id is 1 then it means it is superUser then need to get all organizations list
                    if (CurrentUserSession.OrganizationId == 1)
                    {
                       // objCOrganization = new COrganization() { OrganizationId = pnOrgId, SortOn = pstrSortOn, SortType = pstrSortType,RowSize= pnPageSize, PageNumber = pnPageNo };

                        MOrganization objMOrganization = new MOrganization();

                        objGOrganization = objMOrganization.GetOrganizationGridList(objCOrganization, AuthenticationContext);

                        if (objGOrganization.LstCOrganization != null)
                        {
                            if (objGOrganization.LstCOrganization.Count > 0)
                            {
                                objGOrganization.LstCOrganization.ForEach(org =>
                                {
                                    org.CreatedByName = GetFullName(org.CreatedBy);
                                    org.ModifiedByName = GetFullName(org.ModifiedBy);
                                    org.SoftLockedByName = GetFullName(org.SoftLockedBy);
                                    org.HardLockedByName = GetFullName(org.HardLockedBy);
                                });
                            }
                        }
                        
                        // if status is true get object of the record to be selected in the list.
                        // first of all we will check the if given record exist in the list.
                        // if given record exist then get the object of that record.
                        // if record not exist in the list then select the first record of the list.
                        if (objGOrganization.Status.Success)
                        {
                            // if status is true get object of the record to be selected in the list.
                            // first of all we will check the if given record exist in the list.
                            // if given record exist then get the object of that record.
                            // if record not exist in the list then select the first record of the list.
                            if (objGOrganization.LstCOrganization != null)
                            {
                                COrganization objSelectedCUser = objGOrganization.LstCOrganization.Where(m => m.OrganizationId == pnId).DefaultIfEmpty(objGOrganization.LstCOrganization[0]).First();

                                // check if record is not already hard locked or softlocked
                                if (objSelectedCUser.IsSoftLocked == false && objSelectedCUser.IsHardLocked == false)
                                {
                                    objSelectedCUser.CreatedBy = CurrentUserSession.UserId;
                                    objGOrganization.Status = objMOrganization.SetOrganizationSoftLock(objSelectedCUser, AuthenticationContext);
                                    if (objGOrganization.Status.Success)
                                    {
                                        // updating the list with softlock details
                                        objGOrganization.LstCOrganization.Where(m => m.OrganizationId == objSelectedCUser.OrganizationId).First().IsSoftLocked = true;
                                        objGOrganization.LstCOrganization.Where(m => m.OrganizationId == objSelectedCUser.OrganizationId).First().SoftLockedBy = CurrentUserSession.UserId;
                                    }
                                }
                            }


                        }

                        ViewBag.bPagingEnabled = true;
                        ViewBag.bSearchEnabled = true;
                        ViewBag.bNewDeleteEnabled = true;
                        ViewBag.bCopyPasteEnabled = false;
                    }
                    //else get detail for current users organization and show it in grid.
                    else
                    {
                        objCOrganization = new COrganization() { OrganizationId = CurrentUserSession.OrganizationId };

                        MOrganization objMOrganization = new MOrganization();

                        objGOrganization.Status = objMOrganization.GetOrganizationDetail(AuthenticationContext, ref objCOrganization);

                        objGOrganization.LstCOrganization.Add(objCOrganization);
                        //set view bag variables for pagging, new, delete and search.
                        ViewBag.bPagingEnabled = false;
                        ViewBag.bSearchEnabled = false;
                        ViewBag.bNewDeleteEnabled = false;
                        ViewBag.bCopyPasteEnabled = false;
                    }

                    // check if status is true
                    if (objGOrganization.Status.Success)
                    {
                        if (objGOrganization.LstCOrganization != null)
                        {
                            if (objGOrganization.LstCOrganization.Count > 0)
                            {
                                objGOrganization.LstCOrganization[0].SortOn = pstrSortOn;
                                objGOrganization.LstCOrganization[0].SortType = pstrSortType;
                            }
                        }
                        // set the values of sort on and sort type in the view bag.
                        ViewBag.SortType = pstrSortType;
                        ViewBag.SortOn = pstrSortOn;
                        ViewBag.CurrentUser = CurrentUserSession.UserId;
                    }
                }
                else
                {
                    //set status to false and its detail.
                    objGOrganization.Status.Success = false;
                    objGOrganization.Status.StatusDetails = SessionState;
                }
            }
            catch (Exception ex)
            {
                // catch the exceptions in any step ,if any 
                //set status to false and its detail as exception message.
                objGOrganization.Status.Success = false;
                objGOrganization.Status.StatusDetails = ex.Message;
            }

            //check if status is true then return list view(partial view of list) else return object with false status.
            if (objGOrganization.Status.Success)
                return PartialView("_list", objGOrganization);
            else
                return Json(objGOrganization);
        }

        [HttpPost]
        public ActionResult SetHardLock(int pnId)
        {
            GOrganization objGOrganization = new GOrganization();

            objGOrganization.Organization = new COrganization();

            objGOrganization.Organization.OrganizationId = pnId;
            try
            {
                //call CheckSession to get session status
                string SessionState = CheckSessionState();
                //IsDisabled checks whether cureently selected row is hardlocked or softlocked by other
                ViewBag.IsDisabled = true;
                ViewBag.IsNew = false;
                //check if session state is ok else return false status to view.
                if (SessionState == CAppConstants.SessionSuccess)
                {
                    MOrganization objMOrganization = new MOrganization();
                    objGOrganization.Organization.CreatedBy = CurrentUserSession.UserId;
                    objGOrganization.Status = objMOrganization.SetOrganizationHardLock(objGOrganization.Organization, AuthenticationContext);
                    
                }
                else
                {
                    objGOrganization.Status = new CStatus();
                    objGOrganization.Status.Success = false;
                    objGOrganization.Status.StatusDetails = SessionState;
                }
            }
            catch (Exception ex)
            {

                objGOrganization.Status = new CStatus();
                objGOrganization.Status.Success = false;
                objGOrganization.Status.StatusDetails = ex.Message;
            }

            return Json(objGOrganization.Status);
        }

        [HttpPost]
        public ActionResult ReleaseHardLock(int pnId)
        {
            GOrganization objGOrganization = new GOrganization();

            objGOrganization.Organization = new COrganization();

            objGOrganization.Organization.OrganizationId = pnId;
            try
            {
                //call CheckSession to get session status
                string SessionState = CheckSessionState();
                //IsDisabled checks whether cureently selected row is hardlocked or softlocked by other
                ViewBag.IsDisabled = true;
                ViewBag.IsNew = false;
                //check if session state is ok else return false status to view.
                if (SessionState == CAppConstants.SessionSuccess)
                {
                    MOrganization objMOrganization = new MOrganization();
                    objGOrganization.Organization.CreatedBy = CurrentUserSession.UserId;
                    objGOrganization.Status = objMOrganization.ReleaseOrganizationHardLock(objGOrganization.Organization, AuthenticationContext);
                }
                else
                {
                    objGOrganization.Status = new CStatus();
                    objGOrganization.Status.Success = false;
                    objGOrganization.Status.StatusDetails = SessionState;
                }
            }
            catch (Exception ex)
            {

                objGOrganization.Status = new CStatus();
                objGOrganization.Status.Success = false;
                objGOrganization.Status.StatusDetails = ex.Message;
            }

            return Json(objGOrganization.Status);
        }

        [HttpPost]
        public ActionResult ReleaseSoftLock(int pnId)
        {

            GOrganization objGOrganization = new GOrganization();

            objGOrganization.Organization = new COrganization();

            objGOrganization.Organization.OrganizationId = pnId;
            try
            {
                //call CheckSession to get session status
                string SessionState = CheckSessionState();
                //IsDisabled checks whether cureently selected row is hardlocked or softlocked by other
                ViewBag.IsDisabled = true;
                ViewBag.IsNew = false;
                //check if session state is ok else return false status to view.
                if (SessionState == CAppConstants.SessionSuccess)
                {

                    //check if Id param is 0 means new is clicked then set selected row object to new.
                    if (0 == pnId)
                    {
                        if (checkUserPermission(CUserPermissionsConstants.OrganizationUpdate))
                        {
                            //here we will append new form to create new organisation
                            ViewBag.IsNew = true;
                            objGOrganization.Status.Success = true;
                        }
                        else
                        {
                            objGOrganization.Status.Success = false;
                            objGOrganization.Status.StatusDetails = CAppErrorsConstants.NoPermission;
                        }
                    }
                    else
                    {
                        MOrganization objMOrganization = new MOrganization();
                        objGOrganization.Organization.CreatedBy = CurrentUserSession.UserId;
                        objGOrganization.Status = objMOrganization.ReleaseOrganizationSoftLock( objGOrganization.Organization,AuthenticationContext);
                    }
                }
                else
                {
                    objGOrganization.Status = new CStatus();
                    objGOrganization.Status.Success = false;
                    objGOrganization.Status.StatusDetails = SessionState;
                }
            }
            catch (Exception ex)
            {

                objGOrganization.Status = new CStatus();
                objGOrganization.Status.Success = false;
                objGOrganization.Status.StatusDetails = ex.Message;
            }

            return Json(objGOrganization.Status);
        }
    }
}
